<template>
  <BasicTable
    :title="project + ' ' + hub"
    :columns="columns"
    :dataSource="rows"
    :loading="loading"
    striped
    bordered
    showTableSetting
    :pagination="pagination"
    :resizeHeightOffset="24"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'status'">
        <a-switch
          :disabled="!can('changeSensorStatus')"
          v-model:checked="record.status"
          @change="onChangeStatus($event, record.id)"
          :checkedValue="1"
          :unCheckedValue="0"
        />
      </template>
      <template v-if="column.key === 'action'">
        <span class="">
          <a class="mx-2" v-if="can('editSensorTh')" @click="onEdit(record)">编辑</a>
          <a class="ml-4">查看</a>
        </span>
      </template>
    </template>

    <template #toolbar>
      <a-button v-if="can('batchSetSensorTh')" type="primary" @click="onSetup"> 批量设置 </a-button>
    </template>
  </BasicTable>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, watch } from 'vue';
import { BasicTable } from '/@/components/Table';
import { getCols } from './tableData';
import { defHttp } from '/@/utils/http/axios';
import { message } from 'ant-design-vue';
import { usePermission } from '/@/hooks/web/usePermission';

export default defineComponent({
  props: {
    project: { type: String },
    hub: { type: String },
    rows: { type: Array },
  },
  components: { BasicTable },
  setup(props, { emit }) {
    const loading = ref(false);
    const pagination = ref<any>(true);
    const { project, hub, rows } = toRefs(props);
    const { can } = usePermission();

    watch(project, load);

    watch(hub, load);

    function load() {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 500);
    }

    const onEdit = (row) => {
      emit('on-edit', row);
    };

    function onChangeStatus(e, id) {
      defHttp.post({ url: '/sensor/change-status', params: { id, status: e } }).then((res) => {
        message.success('修改成功');
      });
    }

    function onSetup() {
      emit('on-setup', rows.value);
    }

    return {
      columns: getCols(),
      loading,
      pagination,
      project,
      hub,
      onEdit,
      rows,
      onChangeStatus,
      onSetup,
      can,
    };
  },
});
</script>
